//
//  WFFarmDao.m
//  WisdomFarm
//
//  Created by sky on 2017/12/14.
//  Copyright © 2017年 sky. All rights reserved.
//

#import "WFFarmDao.h"
#import <AVOSCloud/AVOSCloud.h>

NSString *const WFRemoteFarmKey = @"UserFarm";

@implementation WFFarmDao

- (void)saveFarm:(WFFarm *)farm forUser:(NSString *)userId completion:(void (^)(NSError *error))completion {
    AVObject *remoteFarm = [self AVFarmFromWFFarm:farm userId:userId];
    [remoteFarm saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        if (completion) {
            completion(error);
        }
    }];
}

- (void)farmListByUserId:(NSString *)userId completion:(void (^)(NSArray<WFFarm *> *, NSError *))completion {
    AVQuery *query = [AVQuery queryWithClassName:WFRemoteFarmKey];
    [query whereKey:@"uid" equalTo:@([userId integerValue])];
    [query findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        NSMutableArray *farms = [NSMutableArray new];
        for (AVObject * obj in objects) {
            WFFarm *farm = [self WFFarmFromAVFarm:obj];
            if (!farm) {
                continue;
            }
            [farms addObject:farm];
        }
        if (completion) {
            completion(farms, error);
        }
    }];
}

- (void)farmById:(NSString *)farmId completion:(void (^)(WFFarm *, NSError *))completion {
    AVQuery *query = [AVQuery queryWithClassName:WFRemoteFarmKey];
    [query whereKey:@"Id" equalTo:@([farmId integerValue])];
    [query getFirstObjectInBackgroundWithBlock:^(AVObject * _Nullable object, NSError * _Nullable error) {
        WFFarm *farm = [self WFFarmFromAVFarm:object];
        if (completion) {
            completion(farm, error);
        }
    }];
}

- (void)deleteFarmByObjectId:(NSString *)dataId completion:(void (^)(BOOL, NSError *))completion {
    NSString *deleteSQL = [NSString stringWithFormat:@"delete from UserFarm where objectId='%@'",dataId];
    [AVQuery doCloudQueryInBackgroundWithCQL:deleteSQL callback:^(AVCloudQueryResult * _Nullable result, NSError * _Nullable error) {
        if (completion) {
            completion(error == nil, error);
        }
    }];
}

- (AVObject *)AVFarmFromWFFarm:(WFFarm *)farm userId:(NSString *)userId {
    AVObject *remoteFarm = nil;
    if (farm.objectId) {
        remoteFarm = [AVObject objectWithClassName:WFRemoteFarmKey objectId:farm.objectId];
    } else {
        remoteFarm = [AVObject objectWithClassName:WFRemoteFarmKey];
    }
    if (farm.id) {
        [remoteFarm setObject:@([farm.id integerValue]) forKey:@"Id"];
    }
    if (farm.uid) {
        [remoteFarm setObject:@([farm.uid integerValue]) forKey:@"uid"];
    }
    [remoteFarm setObject:farm.name forKey:@"name"];
    [remoteFarm setObject:farm.address forKey:@"address"];
    [remoteFarm setObject:@([userId integerValue]) forKey:@"uid"];
    [remoteFarm setObject:@(farm.latitude) forKey:@"lat"];
    [remoteFarm setObject:@(farm.longitude) forKey:@"lon"];
    [remoteFarm setObject:[farm.crops cropIdComponentsJoinedByString:@"#"] forKey:@"cropIds"];
    [remoteFarm setObject:[farm.crops cropNameComponentsJoinedByString:@"#"] forKey:@"crop"];
    
    return remoteFarm;
}

- (WFFarm *)WFFarmFromAVFarm:(AVObject *)farm {
    //不是农场类
    if (![farm.className isEqualToString:WFRemoteFarmKey]) {
        return nil;
    }
    WFFarm *localFarm = [[WFFarm alloc] init];
    localFarm.objectId = farm.objectId;
    localFarm.id = [[farm objectForKey:@"Id"] stringValue];
    localFarm.uid = [[farm objectForKey:@"uid"] stringValue];
    localFarm.name = [farm objectForKey:@"name"];
    localFarm.address = [farm objectForKey:@"address"];
    localFarm.latitude = [[farm objectForKey:@"lat"] doubleValue];
    localFarm.longitude = [[farm objectForKey:@"lon"] doubleValue];

    NSString *cropIds = [farm objectForKey:@"cropIds"];
    NSString *cropNames = [farm objectForKey:@"crop"];
    
    NSArray *cropIdArr = [cropIds componentsSeparatedByString:@"#"];
    NSArray *cropNameArr = [cropNames componentsSeparatedByString:@"#"];

    NSInteger count = MIN(cropIdArr.count, cropNameArr.count);
    NSMutableArray *farmCrops = [NSMutableArray new];
    for (NSInteger i = 0; i < count; i++) {
        NSString *ids = cropIdArr[i];
        NSString *names = cropNameArr[i];
        NSArray *idArr = [ids componentsSeparatedByString:@"."];
        NSArray *nameArr = [names componentsSeparatedByString:@"/"];
        if (idArr.count != 2 || nameArr.count != 2) {
            continue;
        }
        NSString *cropId = idArr[0];
        NSString *phaseId = idArr[1];
        NSString *cropName = nameArr[0];
        NSString *phaseName = nameArr[1];
        
        WFFarmCrop *farmCrop = [[WFFarmCrop alloc] init];
        farmCrop.farmId = localFarm.id;
        farmCrop.cropId = cropId;
        farmCrop.phaseId = phaseId;
        farmCrop.cropName = cropName;
        farmCrop.phaseName = phaseName;
        [farmCrops addObject:farmCrop];
    }
    localFarm.crops = farmCrops;
    return localFarm;
}

@end
